package com.spark.gaea.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public final class SerializeUtil {
	private static final Logger LOG;

	public static Object deserialize(final byte[] bytes) {
		Object result = null;
		if (isEmpty(bytes)) {
			return null;
		}
		try {
			final ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
			try {
				final ObjectInputStream objectInputStream = new ObjectInputStream(byteStream);
				try {
					result = objectInputStream.readObject();
				} catch (ClassNotFoundException ex) {
					throw new Exception("Failed to deserialize object type", ex);
				}
			} catch (Throwable ex2) {
				throw new Exception("Failed to deserialize", ex2);
			}
		} catch (Exception e) {
			SerializeUtil.LOG.error("Failed to deserialize", e);
		}
		return result;
	}

	public static boolean isEmpty(final byte[] data) {
		return data == null || data.length == 0;
	}

	public static byte[] serialize(final Object object) {
		byte[] result = null;
		if (object == null) {
			return new byte[0];
		}
		try {
			final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128);
			try {
				if (!(object instanceof Serializable)) {
					throw new IllegalArgumentException(
							SerializeUtil.class.getSimpleName() + " requires a Serializable payload "
									+ "but received an object of type [" + object.getClass().getName() + "]");
				}
				final ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream);
				objectOutputStream.writeObject(object);
				objectOutputStream.flush();
				result = byteStream.toByteArray();
			} catch (Throwable ex) {
				throw new Exception("Failed to serialize", ex);
			}
		} catch (Exception ex2) {
			SerializeUtil.LOG.error("Failed to serialize", ex2);
		}
		return result;
	}

	static {
		LOG = LoggerFactory.getLogger(SerializeUtil.class);
	}
}
